package com.sdr.takepicplugin;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by homelajiang on 2016/9/8 0008.
 */
public class FileUploadManger {

    private static FileUploadManger manger;
    private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private static final String PREFIX = "--";
    private static final String LINE_END = "\r\n";
    private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private final Context context;
    //	private static final String CONTENT_TYPE = "	application/x-www-form-urlencoded"; // 内容类型
    private int readTimeOut = 10 * 1000; // 读取超时
    private int connectTimeout = 10 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    public static final int UPLOAD_SUCCESS_CODE = 1;    //上传成功
    public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;//文件不存在
    public static final int UPLOAD_SERVER_ERROR_CODE = 3;//服务器出错
    private String url;
    private Map<String, String> params;
    private List<UploadFile> uploadFiles;
    private OnUploadListener onUploadListener;

    public FileUploadManger(Context context) {
        this.context = context;
    }

    public void upload(String url, Map<String, String> params, List<UploadFile> uploadFiles) {
        this.url = url;
        this.params = params;
        this.uploadFiles = uploadFiles;

        new uploadTask().execute();
    }

    public void setUploadListener(OnUploadListener onUploadListener) {
        this.onUploadListener = onUploadListener;
    }

    public interface OnUploadListener {
        void onResult(JSONObject resJson);
    }


    class uploadTask extends AsyncTask<Void, Integer, JSONObject> {

        @Override
        protected JSONObject doInBackground(Void... par) {

            try {
                URL u = new URL(url);
                HttpURLConnection con = (HttpURLConnection) u.openConnection();
                con.setReadTimeout(readTimeOut);
                con.setConnectTimeout(connectTimeout);
                con.setDoOutput(true);
                con.setDoInput(true);
                con.setUseCaches(false);
                con.setRequestMethod("POST");
                con.setRequestProperty("Charset", CHARSET);
                con.setRequestProperty("connection", "keep-alive");
                con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                con.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

                DataOutputStream dos = new DataOutputStream(con.getOutputStream());

                if (params != null && params.size() > 0) {
                    Iterator<String> it = params.keySet().iterator();
                    while (it.hasNext()) {
                        StringBuilder sb = new StringBuilder();
                        sb.append(PREFIX)
                                .append(BOUNDARY)
                                .append(LINE_END);
                        String key = it.next();
                        sb.append("Content-Disposition: form-data; name=\"")
                                .append(key)
                                .append("\"")
                                .append(LINE_END)
                                .append(LINE_END);
                        sb.append(params.get(key))
                                .append(LINE_END);
                        dos.write(sb.toString().getBytes());
                    }
                }

                if (uploadFiles != null && uploadFiles.size() > 0) {
                    for (int i = 0; i < uploadFiles.size(); i++) {
                        UploadFile uploadFile = uploadFiles.get(i);
                        String uriString = uploadFile.getUri().getPath();
                        String fileName = uriString.substring(uriString.lastIndexOf("/") + 1);
                        dos.writeBytes(PREFIX + BOUNDARY + LINE_END);
                        dos.writeBytes("Content-Disposition:form-data; name=\"" + "file"
                                + "\"; filename=\"" + fileName + "\"" + LINE_END);
                        dos.writeBytes("Content-Type:" + uploadFile.getType() + LINE_END);
                        dos.writeBytes(LINE_END);

//                        InputStream fs = context.getContentResolver().openInputStream(uploadFile.getUri());
                        FileInputStream fs = new FileInputStream(new File(uploadFile.getUri().getPath()));
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        int curLen = 0;
                        while ((len = fs.read(buffer)) != -1) {
//                            curLen += len;
                            dos.write(buffer, 0, len);
                        }
                        dos.writeBytes(LINE_END);
                        fs.close();
                    }
                }


                dos.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
                dos.flush();
                dos.close();

                int resCode = con.getResponseCode();
                if (resCode == 200) {
                    InputStream is = con.getInputStream();
                    StringBuilder sb = new StringBuilder();
                    int ss;
                    while ((ss = is.read()) != -1) {
                        sb.append((char) ss);
                    }
                    Log.e("result", sb.toString());
                    return new JSONObject(sb.toString());
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);
            if (onUploadListener != null) {
                onUploadListener.onResult(jsonObject);
            }
        }
    }


}
